package com.atguigu.gulimail.order.web.controller;

import com.atguigu.gulimail.order.service.OrderService;
import com.atguigu.gulimail.order.web.vo.OrderConfirmVO;
import com.atguigu.gulimail.order.web.vo.OrderSubmitVo;
import com.atguigu.gulimail.order.web.vo.SubmitOrderResponseVo;
import io.seata.core.exception.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /**
     * 订单详情页面
     * @param model
     * @return
     */
    @GetMapping ("/toTrade")
    public String toTrade(Model model){

        OrderConfirmVO orderConfirmVO=orderService.getOrderConfirmVo();
        model.addAttribute("confirmOrderData",orderConfirmVO);
        return "confirm";
    }

    /**
     * 提交订单
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder( OrderSubmitVo orderSubmitVo,Model model,RedirectAttributes redirectAttributes) throws TransactionException {
        //下单，创建订单，验证令牌，确认价格，锁库存
        //下单成功转到支付页面
        //下单失败，回到订单详情页面重新确认订单信息

        SubmitOrderResponseVo submitOrderResponseVo=orderService.submitOrder(orderSubmitVo);
        if(submitOrderResponseVo.getCode()==null){
            redirectAttributes.addFlashAttribute("code 为Null");
            return "redirect:http://order.gulimail.com/toTrade";

        }
        if(submitOrderResponseVo.getCode()==0){
            //成功
            model.addAttribute("submitOrderResp",submitOrderResponseVo);
            return "pay";
        }else {
            //失败


            String msg="下单失败：";
            switch (submitOrderResponseVo.getCode()){
                case 1: msg=msg+"幂等令牌验证失败";
                case 2: msg=msg+"锁库存失败";
                case 3: msg=msg+"验价失败" ;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimail.com/toTrade";
        }
    }


}
